<?php


namespace backend\models\c2\entity;


use common\helpers\CodeGenerator;
use common\models\c2\entity\Product;
use common\models\c2\entity\ProductionScheduleItem;
use common\models\c2\statics\ProductionScheduleState;
use common\models\c2\statics\ProductionScheduleType;
use Yii;
use yii\helpers\ArrayHelper;
use yii\validators\RequiredValidator;

class ProcessSchedule extends \common\models\c2\entity\ProductionSchedule
{

    public $items;

    public function rules()
    {
        return ArrayHelper::merge(parent::rules(), [
            // [['producer_id'], 'required'],
            [['items'], 'safe'],
            [['items'], 'validateItems'],
        ]);
    }

    public function validateItems($attribute)
    {
        $items = $this->$attribute;

        foreach ($items as $index => $row) {
            $requiredValidator = new RequiredValidator();
            $error = null;
            $requiredValidator->validate($row['product_id'], $error);
            $requiredValidator->validate($row['enter_product_id'], $error);
            $requiredValidator->validate($row['production_sum'], $error);
            // $requiredValidator->validate($row['enter_sum'], $error);
            if (!empty($error)) {
                $key = $attribute . '[' . $index . '][product_id]';
                // $this->addError($key, Yii::t('app.c2', 'Product/Combination/Package not be null.'));
                $this->addError($key, Yii::t('app.c2', '{attribute} can not be empty!', ['attribute' => Yii::t('app.c2', 'Product')]));
            }
            if (!empty($error)) {
                $key = $attribute . '[' . $index . '][enter_product_id]';
                // $this->addError($key, Yii::t('app.c2', 'Product/Combination/Package not be null.'));
                $this->addError($key, Yii::t('app.c2', '{attribute} can not be empty!', ['attribute' => Yii::t('app.c2', 'Enter Product')]));
            }
            if (!empty($error)) {
                $key = $attribute . '[' . $index . '][production_sum]';
                // $this->addError($key, Yii::t('app.c2', 'Product/Combination/Package not be null.'));
                $this->addError($key, Yii::t('app.c2', '{attribute} can not be empty!', ['attribute' => Yii::t('app.c2', 'Production Sum')]));
            }
            // if (!empty($error)) {
            //     $key = $attribute . '[' . $index . '][enter_sum]';
            //     // $this->addError($key, Yii::t('app.c2', 'Product/Combination/Package not be null.'));
            //     $this->addError($key, Yii::t('app.c2', '{attribute} can not be empty!', ['attribute' => Yii::t('app.c2', 'Enter Sum')]));
            // }
        }
    }


    public function loadDefaultValues($skipIfSet = true)
    {
        parent::loadDefaultValues($skipIfSet); // TODO: Change the autogenerated stub
        if ($this->isNewRecord) {
            $this->code = CodeGenerator::getCodeByDate($this, 'QS');
            $this->type = ProductionScheduleType::PROCESS;
        }
    }

    public function loadItems()
    {
        $this->items = $this->getScheduleItems()->all();
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
        if (!empty($this->items)) {
            foreach ($this->items as $item) {
                $product = Product::findOne($item['product_id']);
                $attributes = [
                    'product_id' => !is_null($product) ? $product->id : 0,
                    'product_name' => !is_null($product) ? $product->name : '',
                    'product_sku' => !is_null($product) ? $product->sku : '',
                    'product_label' => !is_null($product) ? $product->label : '',
                    'product_value' => !is_null($product) ? $product->value : '',
                    'combination_id' => 0,
                    'combination_name' => '',
                    'package_id' => 0,
                    'package_name' => '',
                    'measure_id' => isset($item['measure_id']) ? $item['measure_id'] : 0,
                    'pieces' => 0,
                    'production_sum' => isset($item['production_sum']) ? $item['production_sum'] : 0,
                    'enter_product_id' => isset($item['enter_product_id']) ? $item['enter_product_id'] : 0,
                    'enter_sum' => isset($item['enter_sum']) ? $item['enter_sum'] : 0,
                    'memo' => isset($item['memo']) ? $item['memo'] : '',
                    'position' => isset($item['position']) ? $item['position'] : 0,
                ];
                if (isset($item['id']) && $item['id'] == '') {
                    $itemModel = new ProductionScheduleItem();
                    $itemModel->setAttributes($attributes);
                    $itemModel->link('owner', $this);
                } elseif (isset($item['id'])) {
                    $itemModel = ProductionScheduleItem::findOne($item['id']);
                    if (!is_null($itemModel)) {
                        $itemModel->updateAttributes($attributes);
                    }
                }
            }
        }
    }

    public function setStateToCommit()
    {
        $this->updateAttributes(['state' => ProductionScheduleState::COMMIT]);
    }

    public function setStateToTermination()
    {
        $this->updateAttributes(['state' => ProductionScheduleState::TERMINATION]);
    }

    public function setStateToFinish()
    {
        $this->updateAttributes(['state' => ProductionScheduleState::FINISH]);
    }

}